package system

import (
	"log"
	"mytest/models/request"
	"strings"

	"github.com/casbin/casbin/util"
	"github.com/casbin/casbin/v2"
	adapter "github.com/casbin/gorm-adapter/v3"
)

func Casbin() *casbin.Enforcer {
	ad, err := adapter.NewAdapter("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local", true)
	if err != nil {
		log.Printf("连接数据库错误: %v", err)
		return nil
	}
	e, err := casbin.NewEnforcer("C:\\Users\\hero\\Desktop\\mytest\\service\\system/rbac_model.conf", ad)
	if err != nil {
		log.Printf("初始化casbin错误: %v", err)
		return nil
	}
	e.AddFunction("ParamsMatch", ParamsMatchFunc)
	_ = e.LoadPolicy()
	return e
}
func ParamsMatchFunc(arguments ...interface{}) (interface{}, error) {
	//fmt.Println("args0:", arguments[0]) //这个是请求的
	//fmt.Println("args1", arguments[1])  //这个是数据库的

	key1 := strings.Split(arguments[0].(string), "?")[0]
	return util.KeyMatch2(key1, arguments[1].(string)), nil
}

func UpdateCasbin(receive request.CasbinInReceive) (bool, error) {
	e := Casbin()
	_, err := e.RemoveFilteredPolicy(0, receive.AuthorityId)
	if err != nil {
		log.Println("remove policy", err)
		return false, err
	}
	rules := [][]string{}
	for _, v := range receive.CasbinInfos {
		rules = append(rules, []string{receive.AuthorityId, v.Path, v.Method})
	}

	//rules = append(rules, alreadys...)
	success, err := e.AddPolicies(rules)
	if err != nil || !success {
		log.Println("add policy", err, success)
		return false, err
	}
	return true, nil
}
func GetCasbinById(auId string) (pathMaps []request.CasbinInfo) {
	e := Casbin()
	list := e.GetFilteredPolicy(0, auId)
	for _, v := range list {
		pathMaps = append(pathMaps, request.CasbinInfo{
			Path:   v[1],
			Method: v[2],
		})
	}
	return pathMaps
}
